package com.flst.sql.db;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.flst.entity.Matiere;
import com.flst.sql.MaBaseSQLite;
import com.flst.sql.MatiereDao;

public class MatiereDaoDb implements MatiereDao {

	private SQLiteDatabase base;

	private static final String TABLE = "T_Matiere";
	private static final String COL_ID = "ID";
	private static final String COL_NOM = "nom";

	public MatiereDaoDb(MaBaseSQLite bdd) {
		base = bdd.getReadableDatabase();
	}

	@Override
	public List<Matiere> getAllMatiere() {
		List<Matiere> list_matieres = new ArrayList<Matiere>();

		Cursor c = base.query(TABLE, new String[] { COL_ID, COL_NOM }, null,
				null, null, null, null);

		if (c.moveToFirst()) {
			do {
				list_matieres.add(cursorToMatiere(c));
			} while (c.moveToNext());
		}
		c.close();

		return list_matieres;
	}

	public Matiere cursorToMatiere(Cursor c) {
		Matiere matiere = new Matiere();

		matiere.setId(c.getLong(0));
		matiere.setNom(c.getString(1));

		return matiere;
	}

	@Override
	public Matiere getMatiereById(Long id_matiere) {
		Matiere matiere = new Matiere();

		Cursor c = base.query(TABLE, new String[] { COL_ID, COL_NOM }, COL_ID + " =" + id_matiere,
				null, null, null, null);

		if (c.moveToFirst()) {
			do {
				matiere = cursorToMatiere(c);
			} while (c.moveToNext());
		}
		c.close();

		return matiere;
	}

}
